package electrycity;

import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import java.io.IOException;

public class MyRecordWriter extends RecordWriter<Text, ElectricWritable> {
    private final FSDataOutputStream qsOutputStream;
    private final FSDataOutputStream wzOutputStream;

    public MyRecordWriter(FSDataOutputStream qsOutputStream, FSDataOutputStream wzOutputStream) {
        this.qsOutputStream = qsOutputStream;
        this.wzOutputStream = wzOutputStream;
    }

    @Override
    public void write(Text key, ElectricWritable ele) throws IOException, InterruptedException {
        String year = key.toString();
        if ("2006".equals(year) || "2010".equals(year)) {
            qsOutputStream.write((key + "\t" + ele.getCf() + "\t" +
                    ele.getXy() + "\t" + ele.getKt() + "\t" +
                    ele.getSum() + "\n").getBytes());
        } else {
            wzOutputStream.write((key + "\t" + ele.getCf() + "\t" +
                    ele.getXy() + "\t" + ele.getKt() + "\t" +
                    ele.getSum() + "\n").getBytes());
        }
    }

    @Override
    public void close(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
        qsOutputStream.close();
        wzOutputStream.close();
    }
}
